package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceimpl implements DishService {

    @Autowired
    private DishMapper dishmapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;


    /*
    新增菜品
     */
    @Transactional//保持事务的原子性（说人话就是“一件事要么一起成功要么一起失败”）
    @Override
    public void insert(DishDTO dishDTO) {

        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);

        //向菜品表中插入菜品
        dishmapper.insert(dish);

        //通过前面的insert语句返回从而获得新增的菜品主键
        // （需要在dishmapper中的insert中设置）
        Long id = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();

        //判断是否有传入的口味数据
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });
            //向口味表中插入口味（批量插入）
            dishFlavorMapper.insert(flavors);
        }

    }

    /*
    菜品分页查询
     */
    @Override
    public PageResult queryByPage(DishPageQueryDTO dishPageQueryDTO) {

        //pagehelper插件开始分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        //根据pagehelper规定-mapper查询强制返回Page对象
        Page<DishVO> page = dishmapper.queryByPage(dishPageQueryDTO);


        return new PageResult(page.getTotal(), page.getResult());
    }


    /*
    批量删除菜品
     */
    @Override
    @DeleteMapping
    public void delete(List<Long> ids) {
/*
        //判断菜品是否处于售卖状态 停售后才能删除
        List<Dish> list = dishmapper.getstatus(ids);
        for (Dish dish : list) {
            if (dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }


        //判断菜品是否有关联的套餐 如果有关联的套餐不可以删除
        List<SetmealDish> setmealDishes = dishmapper.setmeal_dish_id(ids);
        for (SetmealDish setmealDish : setmealDishes) {
            if (setmealDish.getSetmealId() != null){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }

        //删除菜品
        dishmapper.delete(ids);

        //删除菜品口味表
        dishFlavorMapper.deleteflavor(ids);

 */


        //判断传入id是否是起售菜品
        for (Long id : ids) {
            Dish dish = dishmapper.getId(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //菜品在起售中 不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断菜品是否关联套餐 关联套餐的菜品不能删除
        List<Long> list = dishmapper.getmeal_dish_id(ids);//根据id菜品id集合查找套餐菜品关系表
        // 从而获取套擦id
        if (list != null && list.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品
        dishmapper.delete(ids);

        //删除菜品口味
        dishFlavorMapper.deleteflavor(ids);


    }

    @Override
    public DishVO getDishData(Long id) {

        //回显菜品数据
        DishVO dishVO = dishmapper.getDishData(id);

        return dishVO;
    }

    @Override
    public void update(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品
        dishmapper.update(dish);

        //修改菜品口味

        //先删除原先所有口味
        dishFlavorMapper.deleteByDishID(dishDTO.getId());

        //插入口味表数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insert(flavors);
        }

    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder().categoryId(categoryId).status(StatusConstant.ENABLE).build();

//        Dish dish1 = dishmapper.queryByID(categoryId);
//
//        List<Dish> list = new ArrayList<>();

        return dishmapper.list(dish);
    }


    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishmapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public void startOrstopDish(Long id) {

        //获取菜品状态
        Integer status = dishmapper.getstatusByid(id);
        if (status == 0){
            //目前在停售状态0 更改为起售1
            Integer code = 1;
            dishmapper.start(code,id);
        }
        else if (status == 1){
            //目前状态在1 更改为0
            Integer code = 0;
            dishmapper.stop(code,id);
        }


        //根据菜品id获取到关联的套餐id 一个菜品可能关联多个套餐（返回的有可能是多个id ）打成集合形式返回
        List<Long> setmealId = dishmapper.getSetmealId(id);

        for (Long setmealid : setmealId) {

            //关联这个菜品的套餐也要停售 传入相关的套餐id和需要更改的状态
            setmealDishMapper.deleteByDish_id( status == 0 ? 1 : 0, setmealid);

        }


    }

    @Override
    public void change(Integer status, Long id) {

        //优化的菜品启停售方法

        //更改菜品启停售状态
        dishmapper.updateStatus(status == 0? 1: 0,id);

        //更改菜品相关套餐状态
        //根据菜品id获取到关联的套餐id 一个菜品可能关联多个套餐（返回的有可能是多个id ）打成集合形式返回
        List<Long> setmealId = dishmapper.getSetmealId(id);

        for (Long setmealid : setmealId) {

            //关联这个菜品的套餐也要停售 传入相关的套餐id和需要更改的状态
            setmealDishMapper.deleteByDish_id( status == 0 ? 1 : 0, setmealid);

        }


    }


}
